package com.aipartner.service.impl;

import com.aipartner.dto.ExampleChatRequest;
import com.aipartner.dto.ExampleDetailResponse;
import com.aipartner.entity.AiImageExample;
import com.aipartner.entity.AiImageExampleChat;
import com.aipartner.entity.AiImageExampleChatLike;
import com.aipartner.mapper.AiImageExampleChatLikeMapper;
import com.aipartner.mapper.AiImageExampleChatMapper;
import com.aipartner.mapper.AiImageExampleMapper;
import com.aipartner.service.AiImageExampleChatService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 示例图聊天服务实现
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiImageExampleChatServiceImpl extends ServiceImpl<AiImageExampleChatMapper, AiImageExampleChat> 
        implements AiImageExampleChatService {
    
    private final AiImageExampleMapper exampleMapper;
    private final AiImageExampleChatLikeMapper likeMapper;
    
    @Value("${app.external-base-url:http://localhost:8080}")
    private String externalBaseUrl;
    
    @Override
    public ExampleDetailResponse getExampleDetail(Long exampleId, Integer page, Integer size, Long currentUserId) {
        // 获取示例图信息
        AiImageExample example = exampleMapper.selectById(exampleId);
        if (example == null) {
            throw new RuntimeException("示例图不存在");
        }
        
        // 转换图片URL为完整路径
        if (example.getImageUrl() != null) {
            String originalUrl = example.getImageUrl();
            String publicUrl = buildPublicUrl(originalUrl);
            example.setImageUrl(publicUrl);
            log.debug("转换示例图片URL: {} -> {}", originalUrl, publicUrl);
        }
        
        // 获取聊天记录
        IPage<AiImageExampleChat> chatPage = getChatPage(exampleId, page, size, currentUserId);
        
        // 构建响应
        ExampleDetailResponse response = new ExampleDetailResponse();
        response.setExample(example);
        response.setChatList(chatPage.getRecords());
        response.setTotal(chatPage.getTotal());
        response.setCurrent(chatPage.getCurrent());
        response.setSize(chatPage.getSize());
        
        return response;
    }
    
    @Override
    public IPage<AiImageExampleChat> getChatPage(Long exampleId, Integer page, Integer size, Long currentUserId) {
        Page<AiImageExampleChat> pageParam = new Page<>(page, size);
        return baseMapper.selectChatPageWithUserInfo(pageParam, exampleId, currentUserId);
    }
    
    @Override
    @Transactional
    public AiImageExampleChat publishChat(Long exampleId, ExampleChatRequest request, Long userId) {
        // 创建聊天记录
        AiImageExampleChat chat = new AiImageExampleChat();
        chat.setExampleId(exampleId);
        chat.setUserId(userId);
        chat.setImageUrl(request.getImageUrl());
        chat.setPrompt(request.getPrompt());
        chat.setStyle(request.getStyle());
        chat.setSize(request.getSize());
        chat.setLikeCount(0);
        chat.setCreateTime(LocalDateTime.now());
        chat.setUpdateTime(LocalDateTime.now());
        
        // 保存到数据库
        boolean saved = save(chat);
        if (!saved) {
            throw new RuntimeException("发布失败");
        }
        
        log.info("用户{}发布了示例图{}的聊天记录: {}", userId, exampleId, chat.getId());
        return chat;
    }
    
    @Override
    @Transactional
    public Boolean toggleLike(Long chatId, Long userId) {
        // 检查是否已点赞
        LambdaQueryWrapper<AiImageExampleChatLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageExampleChatLike::getChatId, chatId)
               .eq(AiImageExampleChatLike::getUserId, userId);
        
        AiImageExampleChatLike existingLike = likeMapper.selectOne(wrapper);
        
        if (existingLike != null) {
            // 取消点赞
            likeMapper.deleteById(existingLike.getId());
            // 更新点赞数
            AiImageExampleChat chat = getById(chatId);
            if (chat != null && chat.getLikeCount() > 0) {
                chat.setLikeCount(chat.getLikeCount() - 1);
                updateById(chat);
            }
            log.info("用户{}取消点赞聊天记录{}", userId, chatId);
            return false;
        } else {
            // 添加点赞
            AiImageExampleChatLike like = new AiImageExampleChatLike();
            like.setChatId(chatId);
            like.setUserId(userId);
            like.setCreateTime(LocalDateTime.now());
            likeMapper.insert(like);
            
            // 更新点赞数
            AiImageExampleChat chat = getById(chatId);
            if (chat != null) {
                chat.setLikeCount(chat.getLikeCount() + 1);
                updateById(chat);
            }
            log.info("用户{}点赞聊天记录{}", userId, chatId);
            return true;
        }
    }
    
    @Override
    public Map<String, Object> getLikeInfo(Long chatId, Long userId) {
        // 获取聊天记录
        AiImageExampleChat chat = getById(chatId);
        if (chat == null) {
            throw new RuntimeException("聊天记录不存在");
        }
        
        // 检查用户是否已点赞
        LambdaQueryWrapper<AiImageExampleChatLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiImageExampleChatLike::getChatId, chatId)
               .eq(AiImageExampleChatLike::getUserId, userId);
        
        boolean liked = likeMapper.selectCount(wrapper) > 0;
        
        Map<String, Object> result = new HashMap<>();
        result.put("liked", liked);
        result.put("likeCount", chat.getLikeCount());
        
        return result;
    }
    
    /**
     * 构建公共访问URL
     */
    private String buildPublicUrl(String path) {
        if (path == null) return null;
        if (path.startsWith("http://") || path.startsWith("https://")) {
            return path;
        }
        
        String base = externalBaseUrl;
        if (base.endsWith("/")) {
            base = base.substring(0, base.length() - 1);
        }
        return base + path;
    }
}
